/**
 *
 *
 * +----------------------------------------------------------------------------------------------+
 * |Date               |  Version  |Author             |Description                              |
 * |==========+=======+==============+===================|
 * |2018年1月28日     |  1.0.0       | kreo                 |Initial                                       |
 * +----------------------------------------------------------------------------------------------+
 */
package main.java.utils.hxy.thread.thread.sql;

import com.jfinal.log.Logger;
import com.wanma.framework.common.service.CommonService;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 注意,暂时不支持参数 , 只能执行SQL
 * 
 * @ClassName StatmentTask
 * @Description
 * 
 */
public class ISQLTask implements Callable<ISQLObject> {
	private static Logger log = Logger.getLogger(ISQLTask.class);
	private final boolean debug = false; // 调试模式
	private ISQLObject sqlObject;
	private CountDownLatch latch; // 阻断式Task

	public ISQLTask(ISQLObject sqlObject) {
		this.sqlObject = sqlObject;
	}

	public ISQLTask(ISQLObject sqlObject, CountDownLatch latch) {
		this.sqlObject = sqlObject;
		this.latch = latch;
	}

	@Override
	public ISQLObject call() {
		try {
			Integer count = 0;
			if (!debug) {
				long startTime = System.currentTimeMillis();
				count = CommonService.me.updateSQLAt(sqlObject.getDbName(), sqlObject.getSql(), sqlObject.getPara());
				sqlObject.setStatus(count > 0 ? ISQLObject.SUCCESS : ISQLObject.WARN);
				sqlObject.setCount(count);
				long endTime = System.currentTimeMillis();
				log.debug("[" + sqlObject.getMark() + "][Time:" + ((endTime - startTime) * 1.0 / 1000.0) + "s][Count:" + count + "]");
			} else {
				Random random = new Random();
				int sleepTime = 1000 + random.nextInt(4000);
				Thread.sleep(sleepTime);// 进程随机暂停1000~5000ms
				sqlObject.setStatus(ISQLObject.SUCCESS);
				sqlObject.setCount(sleepTime);
			}
		} catch (Exception e) {
			sqlObject.setStatus(ISQLObject.ERROR);
			sqlObject.setResult(e.getMessage());
			log.error("[" + sqlObject.getDbName() + "]\n[SQL:]" + sqlObject.getSql() + "\n[Para:]" + sqlObject.getPara(), e);
		} finally {
			if (this.latch != null) {
				this.latch.countDown();
			}
			if (debug) {
				System.out.println(sqlObject);
			}
		}
		return sqlObject;
	}
}
